#!/usr/bin/env python
"""

   commify

        prints an integer with commas



   Copyright (C) 2007 Leo Goodstadt

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; version 2
   of the License

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
"""


"""
#
# 	Adds commas or a user specified string
# 		every three digits
#
#
import re
four_digits_regex = re.compile(r"\d{4}")
three_digits = r"(.*)(\d{3})"
three_digits_regex = re.compile(three_digits)
def comma(number, delimiter = ','):
    number = str(number)
    #
    #   ignore fraction after decimal point
    if number.find(".") <> - 1:
        intpart, frac = number.split(".", 2)
        frac = "." + frac
    else:
        intpart = number
        frac = ''

    result = list()
    while four_digits_regex.search(intpart):
        # remove three digits at a time from back
        result.append(three_digits_regex.search(intpart).group(2))
        intpart = three_digits_regex.sub(r"\1", intpart,1)
        #print result, ":" , intpart

    #add last remaining digits
    result.append(intpart)

    #join back up
    result.reverse()
    intpart = delimiter.join(result)

    return intpart + frac
"""

import re

__test__ = {}

re_digits_nondigits = re.compile(r'\d+|\D+')

__test__['re_digits_nondigits'] = r"""

    >>> re_digits_nondigits.findall('$1234.1234')
    ['$', '1234', '.', '1234']
    >>> re_digits_nondigits.findall('1234')
    ['1234']
    >>> re_digits_nondigits.findall('')
    []

"""
def comma(value):
    return format_with_commas("%.12g", value)
def commify(value):
    return format_with_commas("%.12g", value)
def format_with_commas(format, value):
    """

    >>> FormatWithCommas('%.4f', .1234)
    '0.1234'
    >>> FormatWithCommas('%i', 100)
    '100'
    >>> FormatWithCommas('%.4f', 234.5678)
    '234.5678'
    >>> FormatWithCommas('$%.4f', 234.5678)
    '$234.5678'
    >>> FormatWithCommas('%i', 1000)
    '1,000'
    >>> FormatWithCommas('%.4f', 1234.5678)
    '1,234.5678'
    >>> FormatWithCommas('$%.4f', 1234.5678)
    '$1,234.5678'
    >>> FormatWithCommas('%i', 1000000)
    '1,000,000'
    >>> FormatWithCommas('%.4f', 1234567.5678)
    '1,234,567.5678'
    >>> FormatWithCommas('$%.4f', 1234567.5678)
    '$1,234,567.5678'
    >>> FormatWithCommas('%i', -100)
    '-100'
    >>> FormatWithCommas('%.4f', -234.5678)
    '-234.5678'
    >>> FormatWithCommas('$%.4f', -234.5678)
    '$-234.5678'
    >>> FormatWithCommas('%i', -1000)
    '-1,000'
    >>> FormatWithCommas('%.4f', -1234.5678)
    '-1,234.5678'
    >>> FormatWithCommas('$%.4f', -1234.5678)
    '$-1,234.5678'
    >>> FormatWithCommas('%i', -1000000)
    '-1,000,000'
    >>> FormatWithCommas('%.4f', -1234567.5678)
    '-1,234,567.5678'
    >>> FormatWithCommas('$%.4f', -1234567.5678)
    '$-1,234,567.5678'

    """

    parts = re_digits_nondigits.findall(format % (value,))
    for i in xrange(len(parts)):
        s = parts[i]
        if s.isdigit():
            parts[i] = _commify(s)
            break
    return ''.join(parts)

def _commify(s):

    r = []
    for i, c in enumerate(reversed(s)):
        if i and (not (i % 3)):
            r.insert(0, ',')
        r.insert(0, c)
    return ''.join(r)


def unit_test():
    for x in [12345678, 123456789.1, 1234567.23, 123456.23, 12345.23,
              1234.23, 123.23, 12.23, 1.23, 0.23, ]:
        print "%20.10g %20s" %(x, comma(x))


if __name__ == '__main__':
    unit_test()
    chrm = list()
    for x in range(22):
        chrm.append(str(x))
    chrm.append("X")
    chrm.append("Y")
    chrm.append("something_longest02")
    chrm.append("something_longest011")
    print chrm


